package com.yq.interview.study.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ProdConsumer_TratitionDemo
 * @Description TODO
 * 题目：一个初始值为零的变量，两个线程对其交替操作，一个加1一个减1，来5轮
 * 多线程企业级模板口诀： 高并发，高内聚低耦合前提，
 * 1、线程 操纵 资源类
 * 2、判断 干活 唤醒通知
 * 3、严防虚假唤醒（多线程并发下的）。
 * 多线程唤醒要用while判断，if会出现多线程唤醒
 * @Author yaoqiang
 * @Date 2020/11/23 11:02
 * @Version 1.0
 */
public class ProdConsumer_TratitionDemo {
    public static void main(String[] args) {
        //多线程操作一定要有资源类
        ShareData shareData=new ShareData();
        new Thread(()->{
            for (int i=1;i<6;i++){
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();
        new Thread(()->{
            for (int i=1;i<6;i++){
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();


        new Thread(()->{
            for (int i=1;i<6;i++){
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();
        new Thread(()->{
            for (int i=1;i<6;i++){
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }
}

class ShareData{
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();
    //判断
    public void increment() throws Exception {
        lock.lock();
        try {
            //1判断
            while (number!=0){
                //等待  不能生产
                condition.await();

            }
            //2、干活
            number++;
            System.out.println(Thread.currentThread().getName()+number);
            //通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void decrement() throws Exception {
        lock.lock();
        try {
            //1判断
            while (number==0){
                //等待  生产
                condition.await();

            }
            //2、干活
            number--;
            System.out.println(Thread.currentThread().getName()+number);
            //通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}